package com.hank.jms.queue;

import com.hank.common.Constant;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Receiver {
    public static String BROKER_URL="tcp://192.168.0.103:61616";
    public static void main(String[] args){
        //创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(Constant.BROKER_URL);
        Connection connection= null;
        try {
            //通过工厂获取一个连接
            connection = connectionFactory.createConnection();
            connection.start();

            //通过连接创建一个会话,并默认设开启事务,自动确认消息
            Session session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            //通过会话构建一个目的地
            Destination destination=session.createQueue("my-test-queue");
            //再通过session创建一个消息发送者，并设定发送目的地对象
            MessageConsumer consumer=session.createConsumer(destination);

            for (int i = 0; i <50 ; i++) {
                TextMessage message=(TextMessage)consumer.receive();//同步消费
                session.commit();
                System.out.println("Receiver Message >>"+message.getText());
            }
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try{
                if(connection!=null){
                    connection.close();
                    connection=null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}
